package com.zm.openapi.filters;

import com.zm.openapi.enums.CommonEnum;
import com.zm.openapi.bo.AppSecretBo;
import com.zm.openapi.constants.FilterSeq;
import com.zm.openapi.constants.OpenApiConstants;
import com.zm.openapi.exception.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * 启动的时候从运营平台把相关的 appid + secret 等信息缓存过来
 * 并做定时失效处理
 * 可以用 guava.cache 来处理
 *
 *
 */
@Slf4j
@Component
public class RequestLimitFilter implements GlobalFilter, Ordered {
    @Value("${api.request.frequency.timewindow:1}")
    private int requestFrequencyTimeWindow; // 限流的时间窗口

    private static final TimeUnit timeUnit = TimeUnit.SECONDS; // 时间单位
    private static final int increaseStep = 1;

    @Autowired
    private RedisTemplate<String, Integer> redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        AppSecretBo appSecretBo = (AppSecretBo) exchange.getAttributes().get(OpenApiConstants.APP_SECRET_OBJECT);
        //
        log.debug("do some frequency validate...");

        String appid = serverHttpRequest.getHeaders().getFirst(OpenApiConstants.APP_ID);
//        String sourceSystem = serverHttpRequest.getHeaders().getFirst(OpenApiConstants.SOURCE_SYSTEM);

        if(StringUtils.isEmpty(appid)) {
            log.error(CommonEnum.ERROR_APPID_NULL.getMsg());
            return Mono.error(new ValidationException(CommonEnum.ERROR_APPID_NULL));
        }

        boolean outFreq = isFrequency( appid, appSecretBo.getFrequency());
        if(outFreq) {
            log.error(CommonEnum.ERROR_REQUEST_FREQUENCY.getMsg());
            return Mono.error(new ValidationException(CommonEnum.ERROR_REQUEST_FREQUENCY));
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return FilterSeq.SEQ_THIRD;
    }



    private boolean isFrequency( String appid, int frequency) {
        boolean res = Boolean.FALSE;
        String key = OpenApiConstants.OPEN_API + ":" + OpenApiConstants.FREQUENCY + ":" + OpenApiConstants.APP_ID + ":" + appid ;
        Integer value = redisTemplate.opsForValue().get(key);
        if(value != null) {
            if(value.intValue() >= frequency) {
                res = Boolean.TRUE;
            } else {
                // 否则请求计数加1
                redisTemplate.opsForValue().increment(key);
            }
        } else {
            // 请求计数从 1 开始
            // 并设置 requestFrequencyTimeWindow 秒后失效
            redisTemplate.opsForValue().set(key, increaseStep, requestFrequencyTimeWindow, timeUnit);

        }
        return res;
    }
}
